package subject_set.offer100;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author haomin
 * @date 2022/10/15 11:55
 **/
public class Offer32_Ⅱ {
    class Solution {
        List<List<Integer>> res = new LinkedList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root == null) return res;
            Deque<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while(!q.isEmpty()){
                int size = q.size();
                List<Integer> list = new ArrayList<>();
                for(int i = 0; i < size; ++i){
                    TreeNode cur = q.poll();
                    list.add(cur.val);
                    if(cur.left != null) q.offer(cur.left);
                    if(cur.right != null) q.offer(cur.right);
                }
                res.add(list);
            }
            return res;
        }
    }
    class Solution2 {
        List<List<Integer>> res = new LinkedList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            preOrder(root, 0);
            return res;
        }
        private void preOrder(TreeNode root, int k){
            if(root == null) return;
            if(res.size() <= k) res.add(new LinkedList<>());
            res.get(k).add(root.val);
            preOrder(root.left, k + 1);
            preOrder(root.right, k + 1);
        }
    }
}